package com.woniuxy.listener;

import com.woniuxy.service.ActitvityService;
import com.woniuxy.service.FoodService;
import com.woniuxy.service.LiuService;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Autowired
    private ActitvityService actitvityService;
    @Resource
    private LiuService liuService;
    @Autowired
    private FoodService foodService;
    private final static Logger logger = LoggerFactory.getLogger(RedisKeyExpirationListener.class);

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @SneakyThrows
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 用户做自己的业务处理即可,注意message.toString()可以获取失效的key
        String key = message.toString();
        System.out.println(key);
        if(key.startsWith("activeOrder#")){
            Integer id = Integer.valueOf(key.substring(key.indexOf("#") + 1));
            actitvityService.updateOrderStatusById(id);
        }else if(key.startsWith("product")){
            Integer id = Integer.valueOf(key.substring(key.indexOf("t") + 1));
            liuService.deleteFromProductOrder(id);
            liuService.deleteFromProductOrderDetail(id);
        }else if(key.startsWith("foodOrder#")){
            Integer id = Integer.valueOf(key.substring(key.indexOf("#") + 1));
            foodService.updateOrderStatusById(id);
        }
    }
}
